/**
 * 作者:hanbo
 * 日期:2018/11/1915:39
 * 描述:
 */
import {VectorBrush} from "./VectorBrush";

/**
 * 点类型片元着色器
 * @type {string}
 */
let FSHADER_SOURCE =
    `#ifdef GL_ES
     #ifdef GL_FRAGMENT_PRECISION_HIGH
     precision highp float;
     #else
     precision mediump float;
     #endif
     #endif
     varying vec4 v_Color;
     void main() {
       float d = distance(gl_PointCoord, vec2(0.5, 0.5));
       if(d < 0.5) {
         gl_FragColor = v_Color;
       } else { discard; }
     }`;
/**
 * 点类型顶点着色器
 * @type {string}
 */
let VSHADER_SOURCE =
    `attribute vec4 a_Position;
     attribute vec4 a_Color;
     attribute float a_PointSize;
     varying vec4 v_Color;
     uniform mat4 u_Matrix;
     void main() {
       gl_Position = u_Matrix * a_Position;
       gl_PointSize = a_PointSize;
       v_Color = a_Color;
     }`;

export class PointsBrush extends VectorBrush {
    constructor(webGL) {
        super(webGL, VSHADER_SOURCE, FSHADER_SOURCE)
    }

    /**
     * 绘制点数组
     * @param float32Array {Float32Array} 缓冲数组
     * @param n {Number} 点数
     */
    drawPoints(float32Array, n) {
        this.verticesColors = float32Array;
        this.n = n;
    }

    draw(projection) {
        super.draw(projection);
        this._compile(this.verticesColors, this.n)
    }

    _compile(verticesColors, n) {
        this.flushData(verticesColors);
        this._webGL.drawArrays(this._webGL.POINTS, 0, n);
    }

    /**
     * 生成缓冲区，设置缓冲区读取方式
     * @param data {Float32Array}
     * @return {number}
     * @override
     */
    flushData(data) {
        this.createBuffer(data);
        const FSIZE = Float32Array.BYTES_PER_ELEMENT;
        let a_Position = this._webGL.getAttribLocation(this._program, 'a_Position');
        if (a_Position < 0) {
            console.error('获取a_Position存储位置失败');
            return -1;
        }

        let a_PointSize = this._webGL.getAttribLocation(this._program, 'a_PointSize');
        if (a_PointSize < 0) {
            console.error('获取a_PointSize存储失败');
            return -1;
        }
        let a_Color = this._webGL.getAttribLocation(this._program, 'a_Color');
        if (a_Color < 0) {
            console.error('获取a_Color存储失败');
            return -1;
        }
        this._webGL.vertexAttribPointer(a_Position, 3, this._webGL.FLOAT, false, FSIZE * 7, 0);
        this._webGL.enableVertexAttribArray(a_Position);
        this._webGL.vertexAttribPointer(a_PointSize, 1, this._webGL.FLOAT, false, FSIZE * 7, FSIZE * 3);
        this._webGL.enableVertexAttribArray(a_PointSize);
        this._webGL.vertexAttribPointer(a_Color, 3, this._webGL.FLOAT, false, FSIZE * 7, FSIZE * 4);
        this._webGL.enableVertexAttribArray(a_Color);
    }

}

